package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.Category;
import com.itheima.bean.Setmeal;
import com.itheima.bean.SetmealDish;
import com.itheima.common.R;
import com.itheima.dao.CategoryDao;
import com.itheima.dao.SetmealDao;
import com.itheima.dao.SetmealDishDao;
import com.itheima.dto.SetmealDto;
import com.itheima.exception.CustomException;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishDao setmealDishDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //1.判断新增的套餐名称是否存在  [根据套餐名称去套餐表中查询统计] 存在：抛出异常提示
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getName, setmealDto.getName());
        int count = this.count(wrapper);
        if (count > 0) {
            throw new CustomException("套餐【" + setmealDto.getName() + "】已经存在");
        }

        //2.保存套餐的基本信息到setmeal表中
        this.save(setmealDto);

        //3.保存套餐的菜品信息到setmeal_dish表中   设置当前套餐下的每个菜品关联当前套餐id
        //获取当前套餐id
        Long setmealId = setmealDto.getId();

        setmealDto.getSetmealDishes().stream().forEach(setmealDish -> {
            //每个菜品关联当前套餐id
            setmealDish.setSetmealId(setmealId);

            setmealDishDao.insert(setmealDish);
        });

    }

    @Override
    public Page<SetmealDto> findPage(Integer page, Integer pageSize, String name) {
        //1.创建Page<SetmealDto>对象
        Page<SetmealDto> setmealDtoPage = new Page<>();

        //2.执行分页查询 完成数据封装
        //2.1：配置MyBatisPlus分页拦截器 【已完成】
        //2.2：创建Page<Setmeal>对象 设置分页查询参数 page、pageSize
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);

        //2.3：创建Wrapper对象 设置查询条件  当套餐名称name不为null时，先根据条件查询，再进行分页
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null && name.length() > 0, Setmeal::getName, name);

        //2.4：调用page方法 传入Page对象和Wrapper对象完成分页查询  将查询出来的数据封装到了Page<Setmeal>对象中
        this.page(setmealPage, wrapper);

        //2.5：将Page<Setmeal>对象中除了records之外的所有属性数据封装到Page<SetmealDto>对象中
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        //2.6：手动设置Page<SetmealDto>对象的records属性
        List<SetmealDto> setmealDtoList = new ArrayList<>();

        List<Setmeal> setmealList = setmealPage.getRecords();
        for (Setmeal setmeal : setmealList) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);

            Category category = categoryDao.selectById(setmeal.getCategoryId());
            setmealDto.setCategoryName(category == null ? "未知" : category.getName());

            setmealDtoList.add(setmealDto);
        }

        setmealDtoPage.setRecords(setmealDtoList);

        //3.返回Page<SetmealDto>对象
        return setmealDtoPage;
    }

    @Override
    public void deleteByIds(Long[] ids) {
        //0.判断ids是否为null 或长度为0
        if (ids == null || ids.length == 0) {
            throw new CustomException("请选择要删除的套餐！！！");
        }

        //1.判断要删除的套餐是否停售 没有：抛出异常提示    this.getBaseMapper()==SetmealDao对象  Arrays.asList:数组工具类 将数组转为list集合
        List<Setmeal> setmealList = this.getBaseMapper().selectBatchIds(Arrays.asList(ids));
        for (Setmeal setmeal : setmealList) {
            if (setmeal.getStatus() == 1) {
                throw new CustomException("当前套餐【" + setmeal.getName() + "】处于启售状态，不能删除！！！");
            }
        }

        //2.根据套餐id删除套餐表setmeal中的套餐基本信息数据
        this.removeByIds(Arrays.asList(ids));

        //3.根据套餐id删除套餐菜品表setmeal_dish中的套餐菜品信息数据  eg:delete from setmeal_dish where setmeal_id in (1,2)
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishDao.delete(wrapper);
    }

    /**
     * 修改数据回显
     *
     * @param id
     * @return
     */
    @Override
    public R<SetmealDto> updateEcho(Long id) {
        //1.根据setmeal的id查询 setmeal
        Setmeal setmeal = this.getById(id);
        //2.根据setmeal的id查询 setmeal_dish
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(wrapper);
        //3.创建setmealdto对象将setmeal复制进去
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        //4.将setmeal_dish 查询结果赋值给setmealdto
        setmealDto.setSetmealDishes(setmealDishList);
        //5.响应数据R
        return R.success(setmealDto);
    }

    /**
     * 修改保存
     *
     * @param setmealDto
     * @return
     */
    @Override
    public R<String> updateWithSetmealDish(SetmealDto setmealDto) {
        //1.设置查询条件判断修改的名称是否唯一
        LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Setmeal::getName, setmealDto.getName()).ne(Setmeal::getId, setmealDto.getId());
        int count = this.count(wrapper1);
        if (count > 0) {
            throw new CustomException("当前[" + setmealDto.getName() + "]已存在");
        }
        //2.修改setmeal数据保存到数据库
        setmealDto.setUpdateTime(LocalDateTime.now());
        boolean b = this.updateById(setmealDto);
        if (!b) {
            throw new CustomException("数据修改失败");
        }
        //3.将setmealDish数据中关联当前setmealId的删除
        LambdaQueryWrapper<SetmealDish> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(wrapper2);
        //4.再将前端获得setmeal_dish关联当前setmealId保存到数据中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            boolean save = setmealDishService.save(setmealDish);
            if (!save) {
                throw new CustomException("数据修改失败");
            }

        });
        return R.success("修改成功");
    }

}
